package com.xiaozhen.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.common.core.domain.system.SysMenu;
import com.xiaozhen.common.core.domain.system.SysTenant;
import com.xiaozhen.common.core.domain.system.SysUser;
import com.xiaozhen.system.dao.SysTenantDao;
import com.xiaozhen.system.dao.SysUserDao;
import com.xiaozhen.system.service.SysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/27 15:24
 * @description:
 */
@Service
public class SysTenantServiceImpl implements SysTenantService {

    @Autowired
    private SysTenantDao sysTenantDao;
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public Page<SysTenant> selectSysTenantList(Page<SysTenant> page) {
        QueryWrapper<SysTenant> queryWrapper = new QueryWrapper<>();
        Page<SysTenant> sysTenantPage = sysTenantDao.selectPage(page, queryWrapper);
        List<SysTenant> sysTenantList = sysTenantPage.getRecords();
        for (SysTenant sysTenant:sysTenantList) {
            Integer userNum = sysUserDao.selectTenantNum(sysTenant.getTenantId());
            sysTenant.setUserNum(userNum);
        }
        return sysTenantPage;
    }

    @Override
    public Boolean checkTenantNameUnique(SysTenant sysTenant) {
        QueryWrapper<SysTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_name", sysTenant.getTenantName());
        List<SysTenant> sysTenants = sysTenantDao.selectList(queryWrapper);
        if (sysTenants.size() == 0) {
            return true;
        } else if (sysTenant.getTenantId() != null && sysTenant.getTenantId().equals(sysTenants.get(0).getTenantId())) {
            return true;
        }
        return false;
    }

    @Override
    public Integer insertSysTenant(SysTenant sysTenant) {
        return sysTenantDao.insert(sysTenant);
    }

    @Override
    public Integer updateSysTenant(SysTenant sysTenant) {
        return sysTenantDao.updateById(sysTenant);
    }

    @Override
    public Integer deleteTenantByIds(Long[] tenantIds) {
        return sysTenantDao.deleteBatchIds(Arrays.asList(tenantIds));
    }
}
